# 百度通用翻译API,不包含词典、tts语音合成等资源，如有相关需求请联系translate_api@baidu.com
# coding=utf-8

import http.client
import hashlib
import sys
import urllib
import random
import json


def translation(word, type):
    """
    通过百度翻译接口进行翻译
    :param word: 输入的词语
    :param type: 'zh'为翻译成中文，'en'为翻译成英文
    :return:
    """
    appid = '20200513000451768'  # 填写你的appid
    secretKey = '1p9fyJW_STlj6jRcQpBK'  # 填写你的密钥

    httpClient = None
    myurl = '/api/trans/vip/translate'

    fromLang = 'auto'  # 原文语种
    toLang = type  # 译文语种
    salt = random.randint(32768, 65536)
    q = word
    sign = appid + q + str(salt) + secretKey
    sign = hashlib.md5(sign.encode()).hexdigest()
    myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(
        q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
        salt) + '&sign=' + sign

    try:
        httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
        httpClient.request('GET', myurl)

        # response是HTTPResponse对象
        response = httpClient.getresponse()
        result_all = response.read().decode("utf-8")
        result = json.loads(result_all)
        # print(result['trans_result'][0]['dst'])
        print(result)
        return result['trans_result'][0]['dst']

    except Exception as e:
        print(e)
    finally:
        if httpClient:
            httpClient.close()


if __name__ == '__main__':
    print(translation(sys.argv[1], sys.argv[2]))
